package com.query.util;

import static org.apache.commons.lang.StringUtils.lowerCase;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import javax.persistence.Table;

import net.vidageek.mirror.Mirror;

@SuppressWarnings("deprecation")
public class EntityUtil {

	public static String nameTableByEntity(Class<?> classe) {
		String textoReturn;
		try {
			textoReturn = findTalbleNameEntityAnnotation(classe);
			if (findTalbleNameEntityAnnotation(classe) != null) {
				return textoReturn;
			} else {
				return createTableName(classe);
			}
		} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static String findTalbleNameEntityAnnotation(Class<?> classe)throws NoSuchMethodException, IllegalAccessException,IllegalArgumentException, InvocationTargetException {
		List<Annotation> annotations = Mirror.on(classe).reflectAll().annotations().atClass();
		for (Annotation annotation : annotations) {
			if (annotation.annotationType().getName().equals(Table.class.getName())) {
				for (Method metodo : annotation.annotationType().getDeclaredMethods()) {
					if (metodo.getName().equals("name")) {
						Object value = metodo.invoke(annotation);
						return value.toString();
					}
				}
			}
		}
		return null;
	}

	private static String createTableName(Class<?> classe) {
		String text = classe.getSimpleName().replaceAll(
				String.format("%s|%s|%s", "(?<=[A-Z])(?=[A-Z][a-z])",
						"(?<=[^A-Z])(?=[A-Z])", "(?<=[A-Za-z])(?=[^A-Za-z])"),
				"_");
		return lowerCase(text);
	}

}
